C++ to find the most characters and times in the string the time complexity is less than O of n^2
- 2020-06-12 10:13:21
- OfStack
Given the string "aabbbcddddeeffffghijklmnopqrst", program to find the most characters and times, requiring a time complexity less than O(n^2)
/********************************************************
Copyright (C), 2016-2017,
FileName: main9
Author: woniu201
Description: Find the number of occurrences of a character in a string
********************************************************/
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void search(char* pData, int len)
{
char counts[1024] = {0}; // The number of times raw data is stored as an index
char bufMax[1024] = {0}; // Used to store characters that appear most often
int max = 0; // The character that appears most often
for (int i=0; i<len; i++)
{
counts[pData[i]] ++;
}
for (int i=0; i<1024; i++)
{
if (counts[i] > max)
{
max = counts[i];
bufMax[0] = i;
}else if ((counts[i] == max) && (counts[i] !=0))
{
bufMax[strlen(bufMax)] = i;
}
}
printf(" The characters that appear most are: ");
for (int i=0; i<strlen(bufMax); i++)
{
printf("%c ", bufMax[i]);
}
printf("\n");
printf(" The number of characters that appear most: %d\n", max);
}
int main()
{
char* srcData = "aabbbcddddeeffffghijklmnopqrst";
search(srcData, strlen(srcData));
getchar();
return 1;
}
conclusion